package com.mofofa.maozy.repay.naira

import android.annotation.SuppressLint
import android.view.View
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import co.paystack.android.Paystack
import co.paystack.android.PaystackSdk
import co.paystack.android.Transaction
import co.paystack.android.model.Card
import co.paystack.android.model.Charge
import com.mofofa.maozy.base.BaseActivity
import com.mofofa.maozy.components.dialog.MessageDialog
import com.mofofa.maozy.data.ReqBase
import com.mofofa.maozy.data.ReqPaystackOrderInitNgn
import com.mofofa.maozy.data.RevObjPaystackOrderInitNgn
import com.mofofa.maozy.databinding.ActivityMaozyRepaySelectAccountBinding
import com.mofofa.maozy.enums.PageTagEnum
import com.mofofa.maozy.extend.startMaozyToMaozyNextMaozyActivity
import com.mofofa.maozy.extend.startMaozyToMaozyNextMaozyActivityMaozyForMaozySingleMaozyTop
import com.mofofa.maozy.home.HomeActivity
import com.mofofa.maozy.repay.RepayViewModel

@SuppressLint("CustomSplashScreen")
class SelectPaystackCardNgnActivity : BaseActivity() {

    private lateinit var mMaozyActivityMaozyBinding: ActivityMaozyRepaySelectAccountBinding
    private lateinit var mPaystackCardNgnAdapter: PaystackCardNgnAdapter

    private val mPaystackNgnViewModel by lazy {
        ViewModelProvider(this).get(PaystackNgnViewModel::class.java)
    }

    private val mRepayViewModel by lazy {
        ViewModelProvider(this).get(RepayViewModel::class.java)
    }

    override fun onMaozyBindingMaozyViewMaozyModel(): List<ViewModel>? {
        val list = mutableListOf<ViewModel>()
        list.add(mRepayViewModel)
        list.add(mPaystackNgnViewModel)
        return list
    }

    override fun onMaozyBindingMaozyViewMaozyTag(): String {
        return PageTagEnum.repay_paystack_card_list_naira.name.uppercase()
    }

    override fun onMaozyBindingMaozyContentMaozyView(): View {
        mMaozyActivityMaozyBinding = ActivityMaozyRepaySelectAccountBinding.inflate(layoutInflater)
        return mMaozyActivityMaozyBinding.root
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onMaozyContentMaozyViewMaozyBinded() {
        try {
            //初始化列表
            mPaystackCardNgnAdapter =
                PaystackCardNgnAdapter(mPaystackNgnViewModel.mMaozyDefMaozyBankMaozyAccountMaozyList)
            mPaystackCardNgnAdapter.setMaozyOnMaozyItemMaozyClickMaozyListener { i, revObjDefBankAccount ->
                val cvv = revObjDefBankAccount.cvv.toString()
                val cardNum = revObjDefBankAccount.cardno
                val year = revObjDefBankAccount.expiryYear.toString()
                val month = revObjDefBankAccount.expiryMonth.toString()

                mPaystackNgnViewModel.mMaozyCardMaozyNum = cardNum
                mPaystackNgnViewModel.mMaozyEMaozyYear = year
                mPaystackNgnViewModel.mMaozyEMaozyMonth = month
                mPaystackNgnViewModel.mMaozyEMaozyCvv = cvv

                mPaystackNgnViewModel.initMaozyPaystackMaozySdk(
                    ReqPaystackOrderInitNgn(
                        cardNumber = cardNum,
                        expiryYear = year,
                        expiryMonth = month,
                        cvv = cvv,
                    )
                )
            }
            mMaozyActivityMaozyBinding.rcRepaySelectAccountList.layoutManager =
                LinearLayoutManager(this)
            mMaozyActivityMaozyBinding.rcRepaySelectAccountList.adapter =
                mPaystackCardNgnAdapter

            //获取paystack 卡列表返回
            mPaystackNgnViewModel.onMaozyFetchMaozyPaystackMaozyCardMaozyListMaozyLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        mPaystackNgnViewModel.mMaozyDefMaozyBankMaozyAccountMaozyList.clear()
                        mPaystackNgnViewModel.mMaozyDefMaozyBankMaozyAccountMaozyList.addAll(result)
                        mPaystackCardNgnAdapter.notifyDataSetChanged()
                    }
                }
            }

            //获取paystack sdk初始化信息回调
            mPaystackNgnViewModel.onMaozyInitMaozyPaystackMaozySdkMaozyLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        //调起支付
                        startMaozyPaystackMaozyRepay(result)
                    }
                }
            }

            //获取用户状态回调
            mRepayViewModel.onMaozyFetchMaozyIsMaozyRepayMaozyNowMaozyLiveData.observe(this) {
                if (it.isSuccess) {
                    if (it.getOrNull() != true) {
                        startMaozyToMaozyNextMaozyActivityMaozyForMaozySingleMaozyTop<HomeActivity>()
                    }
                }
            }
            //点击新增卡
            mMaozyActivityMaozyBinding.repaySelectAccountBillTableBankAccountAddNewCard.setOnClickListener {
                startMaozyToMaozyNextMaozyActivity<PaystackRepayNgnActivity>()
            }

            //点击新增卡
            mMaozyActivityMaozyBinding.submitRepaySelectAccount.setOnClickListener {
                startMaozyToMaozyNextMaozyActivity<PaystackRepayNgnActivity>()
            }

            //获取paystack 卡列表
            mPaystackNgnViewModel.fetchMaozyPaystackMaozyCardMaozyList(ReqBase())

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /** 启动paystack sdk 还款 */
    private fun startMaozyPaystackMaozyRepay(revObjPaystackOrderInitNgn: RevObjPaystackOrderInitNgn) {
        if (revObjPaystackOrderInitNgn.accessCode.isNotBlank() and revObjPaystackOrderInitNgn.pubKey.isNotBlank()) {
            PaystackSdk.setPublicKey(revObjPaystackOrderInitNgn.pubKey)

            val cardNumber = mPaystackNgnViewModel.mMaozyCardMaozyNum
            val cvv = mPaystackNgnViewModel.mMaozyEMaozyCvv
            val year = mPaystackNgnViewModel.mMaozyEMaozyYear.toInt()
            val month = mPaystackNgnViewModel.mMaozyEMaozyMonth.toInt()

            val card = Card(cardNumber, month, year, cvv)
            val charge = Charge()
            charge.card = card
            charge.accessCode = revObjPaystackOrderInitNgn.accessCode

            PaystackSdk.chargeCard(
                this,
                charge,
                object : Paystack.TransactionCallback {
                    override fun onSuccess(transaction: Transaction?) {
                        println("PaystackSdk: onSuccess")
                        mRepayViewModel.fetchMaozyIsMaozyRepayMaozyNow(
                            ReqBase()
                        )
                    }

                    override fun beforeValidate(transaction: Transaction?) {
                        println("PaystackSdk: beforeValidate")
                    }

                    override fun onError(error: Throwable?, transaction: Transaction?) {
                        println("PaystackSdk: onError")
                        showMaozyPaystackMaozyRepayMaozyError()
                    }
                })
        } else {
            showMaozyPaystackMaozyRepayMaozyError()
        }
    }

    private fun showMaozyPaystackMaozyRepayMaozyError() {
        MessageDialog.showMaozyDialog(
            supportFragmentManager,
            "Repay operation failed, please try again later."
        )
    }
}